// <copyright file="Graph.cs" company="Alan Dean">
// The MIT License

// Copyright (c) 2008 Alan Dean

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
// <author>Alan Dean</author>
// <email>alan.dean@thoughtpad.net</email>

namespace Semantic.Collections.Generic
{
    using System;
    using System.Collections;
    using System.Collections.ObjectModel;
    using System.Diagnostics.CodeAnalysis;
    using System.Text;

    using Semantic.Rdf;

    /// <summary>
    /// Represents an RDF Graph.
    /// </summary>
    /// 
    /// <remarks>
    /// <para>An RDF graph is a set of RDF triples.</para>
    /// <para>
    /// The set of nodes  of an RDF graph is the set of subjects and objects of triples in the graph.
    /// </para>
    /// </remarks>
    /// 
    /// <seealso href="http://www.w3.org/TR/rdf-concepts/#section-rdf-graph">RDF Graph</seealso>
    [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is the correct naming.")]
    public class Graph : Collection<ITriple>, IGraph
    {
        #region fields

        /// <summary>
        /// Stores the default <see cref="T:System.Collections.IComparer"/> for this type.
        /// </summary>
        private static readonly IComparer _defaultComparer = new UriReferenceComparer();

        /// <summary>
        /// Stores the <see cref="P:Semantic.Collections.Generic.Graph.Comparer"/> data.
        /// </summary>
        private IComparer _comparer;
        
        #endregion

        #region public Graph()
        /// <overloads>
        /// Overloaded.
        /// Initializes a new instance of the <see cref="T:Semantic.Rdf.Graph"/> class.
        /// </overloads>
        /// 
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Semantic.Rdf.Graph"/> class.
        /// </summary>
        public Graph()
            : this(_defaultComparer)
        {
        }
        #endregion

        #region public Graph(IComparer)
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Semantic.Rdf.Graph"/> class
        /// with the specified <paramref name="comparer"/>.
        /// </summary>
        /// 
        /// <param name="comparer">
        /// The <see cref="T:System.Collections.IComparer"/> for this instance.
        /// </param>
        /// 
        /// <exception cref="T:System.ArgumentNullException">
        /// <paramref name="comparer"/> is a <see langword="null"/> reference.
        /// </exception>
        public Graph(IComparer comparer)
        {
            this.Comparer = comparer;
        }
        #endregion

        #region public IComparer Comparer
        /// <summary>
        /// Gets or sets the <see cref="T:System.Collections.IComparer"/> used by this instance.
        /// </summary>
        /// 
        /// <value>A comparison provider.</value>
        /// 
        /// <exception cref="T:System.ArgumentNullException">
        /// <paramref name="value"/> is a <see langword="null"/> reference.
        /// </exception>
        public IComparer Comparer
        {
            get
            {
                return this._comparer;
            }

            set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }

                this._comparer = value;
            }
        }
        #endregion

        #region public override string ToString()
        /// <summary>
        /// Returns a <see langword="string"/> representation of this instance.
        /// </summary>
        /// <returns>A <see langword="string"/> representation of this instance.</returns>
        public override string ToString()
        {
            StringBuilder buffer = new StringBuilder();

            foreach (ITriple triple in this)
            {
                buffer.Append('<');
                buffer.Append(triple.Subject.LexicalForm);
                buffer.Append("> <");
                buffer.Append(triple.Predicate.LexicalForm);

                IUriReference uri = (triple.Object as IUriReference);
                if (null == uri)
                {
                    buffer.Append("> \"");
                    buffer.Append(triple.Object.ToString());
                    buffer.Append('"');
                }
                else
                {
                    buffer.Append("> <");
                    buffer.Append(uri.LexicalForm);
                    buffer.Append('>');
                }

                buffer.Append(" .");
                buffer.Append(Environment.NewLine);
            }

            return buffer.ToString();
        }
        #endregion

        #region public virtual IGraph Select(IUriReference, IUriReference)
        /// <summary>
        /// Selects all triples from the current graph with matching
        /// <paramref name="subject"/> and <paramref name="predicate"/> values.
        /// </summary>
        /// 
        /// <param name="subject">The triple subject to match.</param>
        /// <param name="predicate">The triple predicate to match.</param>
        /// 
        /// <returns>
        /// An RDF <see cref="T:Semantic.Rdf.Graph"/> containing the selection results.
        /// </returns>
        public virtual IGraph Select(IUriReference subject, IUriReference predicate)
        {
            Graph graph = null;

            if ((null == subject) && (null == predicate))
            {
                graph = this;
            }
            else
            {
                graph = new Graph();
                foreach (ITriple triple in this)
                {
                    if (((null == subject) || (0 == this.Comparer.Compare(subject, triple.Subject)))
                        && ((null == predicate) || (0 == this.Comparer.Compare(predicate, triple.Predicate))))
                    {
                        graph.Add(triple);
                    }
                }
            }

            return graph;
        }
        #endregion
    }
}